package com.zcz.item.config;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Component
public class AuthInterceptor extends HandlerInterceptorAdapter {
    @Value("${ip.aa}")
    private String ip;
    private static String ips;
    @PostConstruct
    public void init() {
        ips = ip;
    }
    //程序执行前的操作
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //获取request对象
        // 拦截代码
        String wip = request.getRemoteAddr();
        System.err.println(wip+"拦截器");
        if (!ips.contains(wip)){
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            JSONObject res = new JSONObject();
            res.put("status","403");
            res.put("msg","您请求的方式不对,服务器拒绝请求");
            PrintWriter out = null ;
            out = response.getWriter();
            out.write(res.toString());
            out.flush();
            out.close();
            return false;
        }
        return true;
    }
}
